define(['jquery', 'bootstrap', 'backend', 'table', 'form','layer'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            var pid = 0
            if($('#pid').length > 0){
                pid = $('#pid').val();
            }

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'yalimedia/course/index?type_id=1&pid='+pid,
                    add_url: 'yalimedia/course/add',
                    edit_url: 'yalimedia/course/edit',
                    del_url: 'yalimedia/course/del',
                    multi_url: 'yalimedia/course/multi',
                    table: 'yalimedia_course',
                }
            });

            var table = $("#table");

            var btnoption = [
                {checkbox: true},
                {field: 'id', title: __('Id'),operate:false},
                {field: 'title', title: __('标题'),operate:'like',align:'left'},
                {field: 'cover', title: __('封面'),operate:false, events: Table.api.events.image,formatter: Table.api.formatter.image },
                {field: 'status', title: __('是否上架'),searchList:{1:__('是'),0:__('否')}, formatter: Table.api.formatter.toggle},
                {field: 'is_hot', title: __('是否推荐'), searchList:{1:__('是'),0:__('否')}, formatter: Table.api.formatter.toggle},
                {field: 'is_buy', title: __('需要购买'), searchList:{1:__('是'),0:__('否')}, formatter: Table.api.formatter.toggle},
                {field: 'taobaolink', title: __('淘宝链接'),formatter: function (value) {
                    return value ? '<a class="text-info" target="_bank" href="'+value+'">'+value+'</a>' : '';
                },perate:false},
                {field: 'createtime', title: __('创建时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

            ];
            if($('#pid').length > 0){

            }else{
                btnoption.push({field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                    buttons: [
                        {
                            name: 'content',
                            title: __('章节内容'),
                            text:'章节内容',
                            extend:'data-area=["100%","100%"]',
                            classname: 'btn btn-xs btn-default btn-dialog',
                            icon: 'fa fa-bars',
                            url: 'yalimedia/course/content'
                        }],
                    formatter: Table.api.formatter.operate})
            }
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                sortOrder:'desc',
                columns: [
                    btnoption
                ]
            });
            $('#selectcourse').click(function () {
                var pid = $('#pid').val()
                Fast.api.ajax({
                    url:  "user/yalimedia_course_user/set_user_course/pid/"+pid,
                    data: {ids:Table.api.selectedids(table)},
                    success:function (res) {
                        if(res && res.code == 1){
                            parent.Toastr.success(res.msg);

                            parent.$("a.btn-refresh").trigger("click");
                            Fast.api.close()
                        }
                        return false
                    }
                });

            })
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        content:function(){

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'yalimedia/course/content?ids='+$("#table").attr('data-id'),
                    multi_url: 'category/multi',
                    table: 'category',
                }
            });


            var table = $("#table");
            var tableOptions = {
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                escape: false,
                pk: 'id',
                sortName: 'id',
                pagination: false,
                commonSearch: false,
                search:false,
                columns: [
                    [


                        {field: 'title', title: __('内容'), align: 'left'},
                        {field: 'operate', title: __('Operate'), width:350, align:'right', table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    visible:function (row) {
                                        if(row['cate'] == "unit"){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                    name: 'content',
                                    title: __('排序'),
                                    text:'排序',
                                    extend:'data-area=["260px","200px"]',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-sort',
                                    url: 'yalimedia/course/unit_sort'
                                },
                                {
                                    visible:function (row) {
                                        if(row['cate'] == "unit"){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                    name: 'content',
                                    title: __('添加内容'),
                                    extend:'data-area=["90%","90%"]',
                                    text:'添加内容',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    icon: 'fa',
                                    url: 'yalimedia/course/add_content?course_id='+$("#table").attr('data-id')
                                },
                                {
                                    visible:function (row) {
                                        if(row['cate'] == "unit"){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                    name: 'content',
                                    title: __('编辑目录'),
                                    text:'编辑目录',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa',
                                    url: 'yalimedia/course/edit_unit'
                                    
                                },{
                                    visible:function (row) {
                                        if(row['cate'] == "unit"){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                    name: 'content',
                                    title: __('删除'),
                                    text:'删除',
                                    classname: 'btn btn-xs btn-danger btn-magic btn-ajax',
                                    icon: 'fa',
                                    url: 'yalimedia/course/del_unit',
                                    confirm: '确认删除吗，不可撤销？',
                                    success: function (data, ret) {
                                        if(ret.code){
                                            table.bootstrapTable('refresh');
                                        }
                                    },
                                },
                                {
                                    visible:function (row) {
                                        if(row['cate'] == "content"){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                    name: 'content',
                                    title: __('排序'),
                                    text:'排序',
                                    extend:'data-area=["260px","200px"]',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-sort',
                                    url: 'yalimedia/course/content_sort'
                                },
                                {
                                    visible:function (row) {
                                        if(row['cate'] == "content"){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                    name: 'content',
                                    extend:'data-area=["90%","90%"]',
                                    title: __('试题分类'),
                                    text:'试题分类',
                                    classname: 'btn btn-xs btn-default btn-dialog',
                                    icon: 'fa',
                                    url: 'yalimedia/coursequestioncategory/index?course_id='+$("#table").attr('data-id')
                                },
                                // {
                                    
                                //     visible:function (row) {
                                        
                                //         if(row['cate'] == "content"){
                                //             return true;
                                //         }else{
                                //             return false;
                                //         }
                                //     },
                                //     name: 'content',
                                //     extend:'data-area=["90%","90%"]',
                                //     title: __('添加试题'),
                                //     text:'添加试题',
                                //     classname: 'btn btn-xs btn-warning btn-dialog',
                                //     icon: 'fa',
                                //     url: 'exam/question/select',
                                //     callback: (data) => {
                                        
                                //         var id = '';
                                //         for (let i = 0; i < data.length; i++) {
                                //             if( i == 0){
                                //                 id += data[i].id;
                                //             }else{
                                //                 id += ','+data[i].id;
                                //             }
                                //         }

                                //         Fast.api.ajax({
                                //             url: 'yalimedia/course/add_question',
                                //             data: {
                                //                 'id':id
                                //             },
                                //             success: function(data) {
                                //                 Layer.closeAll();
                                //                 Toastr.success('添加成功');
                                //             }
                                //         });
                                //     }
                                // },
                                {
                                    visible:function (row) {
                                        if(row['cate'] == "content"){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                    name: 'content',
                                    extend:'data-area=["90%","90%"]',
                                    title: __('编辑目录'),
                                    text:'编辑目录',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa',
                                    url: 'yalimedia/course/edit_content'
                                },
                                {
                                    visible:function (row) {
                                        if(row['cate'] == "content"){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                    name: 'content',
                                    title: __('删除'),
                                    text:'删除',
                                    classname: 'btn btn-xs btn-danger btn-magic btn-ajax',
                                    icon: 'fa',
                                    url: 'yalimedia/course/del_content',
                                    confirm: '确认删除吗，不可撤销？',
                                    success: function (data, ret) {
                                        if(ret.code){
                                            table.bootstrapTable('refresh');
                                        }
                                    },
                            }],formatter: Table.api.formatter.operate}
                    ]
                ]
            };
            // 初始化表格
            table.bootstrapTable(tableOptions);

            // 为表格绑定事件
            Table.api.bindevent(table);

            //绑定TAB事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                // var options = table.bootstrapTable(tableOptions);
                var typeStr = $(this).attr("href").replace('#','');
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    // params.filter = JSON.stringify({type: typeStr});
                    params.type = typeStr;

                    return params;
                };
                table.bootstrapTable('refresh', {});
                return false;

            });

            $(document).on('click', '.btn-unit-add', function () {
                var url = "yalimedia/course/add_unit?course_id="+$(this).attr('data-id');
                Fast.api.open(url, __('添加目录'), {
                    callback:function () {
                        table.bootstrapTable('refresh');
                    }
                });
            });

            Controller.api.bindevent();
        },
        add_unit:function(){
            Controller.api.bindevent();
        },
        edit_unit:function(){
            Controller.api.bindevent();
        },
        add_content:function(){
            $(document).on('change', '#c-type', function () {

                if($(this).val() == 1){
                    $("#video_div").show();
                    $("#content_div,#audio_div").hide();
                }else if($(this).val() == 2){
                    $("#video_div,#audio_div").hide();
                    $("#content_div").show();
                }else if($(this).val() == 3){
                    $("#audio_div").show();
                    $("#content_div,#video_div").hide();
                }
            });

            $("#select-video").click(function(){
                var url = "yalimedia/course/select_video?type=3";
                Fast.api.open(url, __('选择视频'), {
                    area:["80%","80%"],
                    callback:function (data) {

                        // $("#c-video_id").val(data.VideoId);
                        $("#c-video_id").val(data.id);
                        $("#c-video_type").val("video");
                        // $("#c-video_title").val(data.VideoTitle);
                        $("#c-video_title").val(data.title);
                        $("#c-video_cover").val(data.CoverURL);
                    }
                });
            })

            $("#select-audio").click(function(){
                var url = "yalimedia/course/select_video?type=2";
                Fast.api.open(url, __('选择音频'), {
                    area:["80%","80%"],
                    callback:function (data) {

                        $("#c-audio_id").val(data.MediaId);
                        $("#c-audio_title").val(data.AudioTitle);
                    }
                });
            })

            Controller.api.bindevent();
        },
        edit_content:function(){
            $(document).on('change', '#c-type', function () {

                if($(this).val() == 1){
                    $("#video_div").show();
                    $("#content_div,#audio_div").hide();
                }else if($(this).val() == 2){
                    $("#video_div,#audio_div").hide();
                    $("#content_div").show();
                }else if($(this).val() == 3){
                    $("#audio_div").show();
                    $("#content_div,#video_div").hide();
                }
            });

            $("#select-video").click(function(){
                var url = "yalimedia/course/select_video?type=3";
                Fast.api.open(url, __('选择视频'), {
                    area:["80%","80%"],
                    callback:function (data) {
                        // $("#c-video_id").val(data.VideoId);
                        // $("#c-video_type").val("video");
                        // $("#c-video_title").val(data.VideoTitle);
                        console.log(data);
                        $("#c-video_id").val(data.id);
                        $("#c-video_type").val("video");
                        $("#c-video_title").val(data.title);
                    }
                });
            })

            $("#select-audio").click(function(){
                var url = "yalimedia/course/select_video?type=2";
                Fast.api.open(url, __('选择音频'), {
                    area:["80%","80%"],
                    callback:function (data) {
                        $("#c-audio_id").val(data.MediaId);
                        $("#c-audio_title").val(data.AudioTitle);
                    }
                });
            })

            Controller.api.bindevent();
        },
        select_video: function () {
            require(['jstree'], function () {
                var tid=0;
                var cateId;
                var type = $("#box").attr('data-type');
                // 初始化表格参数配置
                Table.api.init({
                    extend: {
                        index_url: 'yalimedia/media/index',
                        table: 'table',
                    }
                });


                var table = $("#table");


                // 初始化表格
                table.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.index_url+'?type='+type,
                    commonSearch:false,
                    pk: 'MediaId',
                    columns: [
                        [
                            {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                                buttons: [{
                                    name: 'content',
                                    title: __('选择'),
                                    text:'选择',
                                    classname: 'btn btn-xs btn-danger btn-click',
                                    click : function (data, ret) {
                                        Fast.api.close(ret);
                                    },
                                }],formatter: Table.api.formatter.operate},
                            // {field: 'URL', title: __('图片'),visible:false,formatter: Table.api.formatter.image,events: Table.api.events.image},
                            // {field: 'ImageTitle', title: __('标题'),visible:false},
                            // {field: 'AudioTitle', title: __('音频')},
                            // {field: 'VideoTitle', title: __('视频'),visible:false},
                            // {field: 'Size', title: __('大小'),visible:false},
                            // {field: 'CoverURL', title: __('视频封面'),visible:false,formatter: Table.api.formatter.image},
                            // {field: 'Status', title: __('状态'),formatter: Controller.api.formatter.status},
                            // {field: 'CreationTime', title: __('上传时间')}
                            {field: 'url', title: __('图片'),formatter: Table.api.formatter.image,events: Table.api.events.image},
                            {field: 'title', title: __('名称')},
                            {field: 'createtime', title: __('上传时间'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                            // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        ]
                    ]
                });

                if(type == 3){
                    // $('#table').bootstrapTable('hideColumn', "URL");
                    // $('#table').bootstrapTable('hideColumn', "AudioTitle");
                    // $('#table').bootstrapTable('hideColumn', "ImageTitle");
                    // $('#table').bootstrapTable('showColumn', "VideoTitle");
                    // $('#table').bootstrapTable('showColumn', "CoverURL");
                    
                    $('#table').bootstrapTable('hideColumn', "url");
                    $('#table').bootstrapTable('showColumn', "CoverURL");
                }else if(type == 2){
                    // $('#table').bootstrapTable('hideColumn', "URL");
                    // $('#table').bootstrapTable('hideColumn', "AudioTitle");
                    // $('#table').bootstrapTable('hideColumn', "ImageTitle");
                    // $('#table').bootstrapTable('hideColumn', "VideoTitle");
                    // $('#table').bootstrapTable('hideColumn', "CoverURL");
                    // $('#table').bootstrapTable('showColumn', "AudioTitle");
                    $('#table').bootstrapTable('hideColumn', "url");
                    $('#table').bootstrapTable('hideColumn', "CoverURL");
                }else if(type == 1){
                    $('#table').bootstrapTable('showColumn', "url");
                    $('#table').bootstrapTable('hideColumn', "CoverURL");
                    $('#table').bootstrapTable('hideColumn', "Size");
                }

                Table.api.bindevent(table);
                $(".nav-tabs a").click(function(){
                    type = $(this).attr('data-type');

                    switch($(this).attr('data-type')){
                        case "2":
                            $("#category_title").html('音频分组');
                            $("#btn_title").html('上传音频');
                            // $('#table').bootstrapTable('hideColumn', "URL");
                            // $('#table').bootstrapTable('hideColumn', "AudioTitle");
                            // $('#table').bootstrapTable('hideColumn', "ImageTitle");
                            // $('#table').bootstrapTable('hideColumn', "VideoTitle");
                            // $('#table').bootstrapTable('hideColumn', "CoverURL");
                            // $('#table').bootstrapTable('showColumn', "AudioTitle");
                            
                            $('#table').bootstrapTable('hideColumn', "url");
                            $('#table').bootstrapTable('hideColumn', "CoverURL");
                            break;
                        case "3":
                            $("#category_title").html('视频分组');
                            $("#btn_title").html('上传视频');
                            // $('#table').bootstrapTable('hideColumn', "URL");
                            // $('#table').bootstrapTable('hideColumn', "AudioTitle");
                            // $('#table').bootstrapTable('hideColumn', "ImageTitle");
                            // $('#table').bootstrapTable('showColumn', "VideoTitle");
                            // $('#table').bootstrapTable('showColumn', "CoverURL");
                            
                            $('#table').bootstrapTable('hideColumn', "url");
                            $('#table').bootstrapTable('showColumn', "CoverURL");
                            break;
                    }
                    
                    
                    table.bootstrapTable('refresh', {url:$.fn.bootstrapTable.defaults.extend.index_url+'?type='+type});
                    $('#channeltree').jstree(true).settings.core.data.data=function (node) {return {'id':node.id,'type':type};};
                    $('#channeltree').jstree(true).refresh();
                    
                    $(".btn-category-edit,.btn-category-del").addClass("disabled");
                    
                })
                
                $('#channeltree').on("changed.jstree", function (e, data) {
                    if(data.node){
                        tid = data.node.id;
                        var cateName  = data.node.text;
                        
                        table.bootstrapTable('refresh', {url: $.fn.bootstrapTable.defaults.extend.index_url+"?cateid="+tid+"&type="+type,pageNumber:1});
                        
                        if(data.node.type != 'total'){
                            cateId = data.node.id;
                            $(".btn-category-edit,.btn-category-del").removeClass("disabled");
                        }else{
                            $(".btn-category-edit,.btn-category-del").addClass("disabled");
                        }
                    }
                    
                    return false;
                });
                
                $('#channeltree').jstree({
                    "checkbox": {"keep_selected_style": false,},
                    "types": {
                        "total": {"icon": "fa fa-folder-o",},
                        "folder": {"icon": "fa fa-folder",},
                        "disabled": {"check_node": false,"uncheck_node": false}
                    },
                    'plugins': ["types"],
                    "core": {
                        "themes": {
                            "stripes": false,
                            "dots": false,//是否显示树连接线
                            "icons": true,//是否显示节点的图标
                        },
                        'check_callback': true,
                        'data':{
                            'url' : 'yalimedia/media/tree',
                            'data' : function (node) {
                                return { 'id' : node.id,'type':type };
                            }
                        }
                    }
                });
            })
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        unit_sort: function () {
            Controller.api.bindevent();
        },
        content_sort: function () {
            Controller.api.bindevent();
        },
        api: {
            formatter:{
                status: function (value, row, index) {
                    switch (value) {
                        case "Normal":
                            return "正常";
                        case "Blocked":
                            return "屏蔽";
                        case "TranscodeFail":
                            return "转码失败";
                        case "Transcoding":
                            return "转码中";
                        case "UploadSucces":
                            return "上传完成";
                        case "UploadFail":
                            return "上传失败";
                        case "Uploading":
                            return "上传中";
                    }
                },
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});